<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    :footer="status == 4 ? false : tr"
  >
    <a-spin :spinning="confirmLoading">
      <div v-if="status != 4">
        <a-form-model ref="form" :model="model" :rules="validatorRules">
          <a-form-model-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="postType"
            label="帖子类型"
          >
            <!-- <a-select v-model="model.postType" placeholder="请选择帖子类型">
              <a-select-option value="">全部</a-select-option>
              <a-select-option value="健康">健康</a-select-option>
              <a-select-option value="姻缘">姻缘</a-select-option>
              <a-select-option value="事业">事业</a-select-option>
              <a-select-option value="财富">财富</a-select-option>
            </a-select> -->
            <a-radio-group v-model="model.postType">
              <a-radio value="健康">
                健康
              </a-radio>
              <a-radio value="姻缘">
                姻缘
              </a-radio>
              <a-radio value="事业">
                事业
              </a-radio>
              <a-radio value="财富">
                财富
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="postContent"
            label="帖子内容"
          >
            <a-textarea
              style="height: 150px;"
              placeholder="请输入帖子内容"
              v-model="model.postContent"
            />
          </a-form-model-item>
          <a-form-model-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="图片"
          >
            <a-upload
              :action="path"
              :headers="{ 'X-Access-Token': token }"
              list-type="picture-card"
              @preview="handlePreview"
              @change="handleChange"
              name="file"
              :file-list="fileList"
            >
              <div v-if="fileList.length < 8">
                <a-icon type="plus" />
                <div class="ant-upload-text" style="font-size: 12px;">
                  上传图片
                </div>
              </div>
            </a-upload>
            <a-modal
              :visible="previewVisible"
              :footer="null"
              @cancel="handleCancels"
            >
              <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div v-else>
        <a-descriptions>
          <a-descriptions-item label="发帖人">
            {{ model.nickname }}
          </a-descriptions-item>

          <a-descriptions-item label="帖子类型">
            {{ model.postType }}
          </a-descriptions-item>
        </a-descriptions>
        <a-descriptions>
          <a-descriptions-item label="帖子内容">
            {{ model.postContent }}
          </a-descriptions-item>
        </a-descriptions>
        <a-descriptions>
          <a-descriptions-item label="图片">
            <img
              v-for="(item, index) in model.postPicture"
              :key="index"
              :src="item.pricturePath"
              style="width: 100px;height: 100px;margin-left: 20px;"
              @click="detailimg(item.pricturePath)"
            />
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction, getAction } from "@/api/manage";
import { imgpath } from "@/api/tsapi";
import moment from "moment";
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default {
  name: "PostInformation2Modal",
  data() {
    return {
      title: "操作",
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      path: imgpath(`sys/common/upload`),
      confirmLoading: false,
      validatorRules: {
        postType: [{ required: true, message: "请输入帖子类型!" }],
        postContent: [{ required: true, message: "请输入帖子内容!" }],
      },
      url: {
        add: "/post/postInformation/add",
        edit: "/post/postInformation/editPostInformation",
        upload: "/sys/common/upload",
        recyclePicture: "/postPicture/postPicture/recyclePicture",
      },
      previewVisible: false,
      previewImage: "",
      upload: "",
      token: localStorage.getItem("token"),
      imglist: [],
      target: process.env.VUE_APP_API_BASE_URL,
      fileList: [],
      status: "",
    };
  },
  created() {
    console.log(this.path, "path");
  },
  methods: {
    add() {
      //初始化默认值
      this.edit({});
      const  obj = {
        postType:'健康'
      }
      this.model = Object.assign({}, obj);
    },
    edit(record, type) {
      console.log(record, type, "record");
      this.title = "查看";
      //判断是否为查看详情
      this.status = type;
      if (record.postPicture != null) {
        record.postPicture.map((item) => {
          console.log(item, "item");
          this.fileList.push({
            uid: item.id,
            name: "image.png",
            status: "done",
            url: item.pricturePath,
          });
        });

        console.log(this.fileList, "filelist");
      }

      this.model = Object.assign({}, record);
      this.visible = true;
    },
    close() {
      this.$emit("close");
      this.visible = false;
      if (this.status != 4) {
        this.$refs.form.clearValidate();
      }
    },
    handleOk() {
      const that = this;
      let brr = [];
      that.fileList.map((res) => {
        console.log(res, "res");
        if (res.url) {
          // const index = res.url.lastIndexOf("/");
          // console.log(index, "index");
          const index = this.target.length;
          const urls = res.url.slice(index);
          brr.push(urls);
        } else {
          brr.push(res.response.message);
        }
      });
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = "";
          let method = "";
          if (!this.model.id) {
            httpurl += this.url.add;
            method = "post";
          } else {
            httpurl += this.url.edit;
            method = "post";
          }

          let params = {
            postInformation: {
              postType: this.model.postType,
              postContent: this.model.postContent,
              id: this.model.id,
              postState: 0,
            },
            pictureLink: this.target,
            picturePaths: brr,
          };
          httpAction(httpurl, params, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit("ok");
                this.imglist = [];
                this.fileList = [];
              } else {
                that.$message.warning(res.message);
              }
            })
            .finally(() => {
              that.confirmLoading = false;
              that.close();
            });
        } else {
          return false;
        }
      });
    },
    handleCancel() {
      let url = this.url.recyclePicture;
      let params = {
        picturePaths: this.imglist,
      };
      let method = "post";
      httpAction(url, params, method).then((res) => {});
      this.close();
      this.fileList = [];
      // this.imglist = [];
    },
    handleCancels() {
      this.previewVisible = false;
    },
    //查看图片
    async handlePreview(file) {
      console.log(file, "file");
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    //上传图片
    async handleChange({ fileList }) {
      this.fileList = fileList;
    },
    //打开图片
    detailimg(path) {
      window.open(path);
    },
  },
};
</script>

<style lang="less" scoped></style>
